import React, { Component } from 'react';
import { Form, DatePicker, Input, Select, Button, Modal, Space, InputNumber, Tooltip } from 'antd';
import { FormOutlined, CloseOutlined, WalletOutlined, WechatOutlined, AlipayOutlined, PayCircleOutlined } from '@ant-design/icons';
import _ from 'lodash';
import { apiGetPetArchivesPage, apiPostPetArchivesAdd, apiGetHotelRooms } from "@/request/hotel";
import PetInfoAdd from "./petinfo";
import { phoneReg } from '@/utils/regexp';
import moment from 'moment';
import CashierModal from '../CashierModal';
import '../../style/style.less';
import FormItem from 'antd/es/form/FormItem';

const { Option } = Select

export default class RoomInfo extends Component {
  constructor(props) {
    super(props);
    this.PetInfoAdd = React.createRef();
    this.discountRef = React.createRef();
    this.formRef = React.createRef();
    this.bindPetFormRef = React.createRef();
    this.cashierFormRef = React.createRef();
    this.state = {
      discountReason: '',
      discountPrice: 0,
      roomName: '',
      petOption: [],
      initialValues: {},
      visible: false,
      days: '',
      bgColor: '#CAF982'
    }
  }
  async componentDidMount() {
    this.getUserPet()
  }

  async getUserPet() {
    const { info, member, hotelDays } = this.props
    let res = await apiGetPetArchivesPage({ pageNo: 1, pageSize: -1, memberId: member.memberId })
    if (res.code === 0) {
      let petArchivesId = ""
      if (res.data.length !== 0) {
        petArchivesId = res.data[0].petArchivesId
      }
      this.setState({
        discountPrice: info.serviceRealPrice,
        petOption: res.data,
        roomName: info.serviceName + '-' + info.roomName,
        days: hotelDays,
        roomId: info.roomId,
        initialValues: {
          ...info,
          petName: petArchivesId,
          memberName: member.nickName,
          memberMobile: member.memberMobile
        },
      }, () => {
        this.formRef.setFieldsValue({ ...this.state.initialValues })
        this.onValuesChange({ petName: petArchivesId })
      })
    } else {
      this.onValuesChange({ petName: null })
    }
  }

  outCar(info) {
    this.props.outCar(info)
  }
  // 新建并绑定宠物
  createPet = () => {
    this.setState({
      visible: true
    })
  }
  // 购物车新建宠物
  createBindPet = async (values) => {
    const { memberId } = this.props.member
    let res = await apiPostPetArchivesAdd({ memberId, ...values })
    if (res.code === 0) {
      React.$message({
        type: 'success',
        content: '新建并绑定宠物成功！'
      })
      this.getUserPet()
      this.onCancel()
    } else {
      // 重置 loading
      this.PetInfoAdd.current.resetLoading()
    }
  }
  // 取消新建宠物
  onCancel = () => {
    // 重置 form 表单
    this.setState({
      visible: false
    })
    this.PetInfoAdd.current.resetForm()
  }

  // 入住时间禁止选择
  disabledDate = (current) => {
    // Can not select days before today and today
    let tooLate = current && current.diff(moment().subtract(2, 'days'), 'days') > 1
    let tooEarly = current && current < moment().subtract(2, 'days')
    return !!tooEarly
    // return !!tooLate || !!tooEarly
  };
  // 离店时间禁止选择
  disabledDateEnd = (current) => {
    let beginTime = this.formRef.getFieldsValue('beginTime')
    if (beginTime) {
      return current && current < moment(beginTime).endOf('day') + 1;
    }
    return current && current < moment().endOf('day') + 1;
  }
  getNewPrice = async () => {
    const { info } = this.props
    const { roomId } = this.state
    let formValue = this.formRef.getFieldsValue()
    if (formValue.beginTime && formValue.endTime) {
      formValue.beginTime = moment(formValue.beginTime).format('YYYY-MM-DD')
      formValue.endTime = moment(formValue.endTime).format('YYYY-MM-DD')
      let res = await apiGetHotelRooms({
        ...formValue, roomId
      })
      if (res.code === 0) {
        this.setState({
          discountPrice: res.data.roomStatusVos[0].serviceRealPrice,
          days: res.data.days
        }, () => {
          let item = []
          res.data.roomStatusVos.map(v => {
            v.roomInfoVos.map(item2 => {
              if ([1, 3].includes(item2.roomStatus)) {
                this.setState({
                  bgColor: '#F59A23'
                })
              } else {
                if (item2.roomStatusDateVoList.length > 0) {
                  this.setState({
                    bgColor: '#EC808D'
                  })
                } else {
                  this.setState({
                    bgColor: '#CAF982'
                  })
                }
              }
              item.push({ ...v, ...item2, ...formValue, ordermsg: formValue })
            })
          })
          this.props.getValues(item)
        })
      }
    }

    // else{
    //     this.props.outCar(info)
    // }

  }

  // 表单校验
  onFinish = () => {
    return this.formRef.validateFields()
  }
  propsOrder = () => {
    const { info } = this.props
    let formValue = this.formRef.getFieldsValue()
    if (!formValue.petName) {
      return
    }
    formValue.beginTime = moment(formValue.beginTime).format('YYYY-MM-DD')
    formValue.endTime = moment(formValue.endTime).format('YYYY-MM-DD')
    let roomStatusVos = info
    roomStatusVos.ordermsg = formValue
    this.props.getValues([roomStatusVos])
  }

  onValuesChange(changedValues, allValues) {
    if (changedValues.hasOwnProperty('beginTime') && changedValues.beginTime !== null || changedValues.hasOwnProperty('endTime') && changedValues.endTime !== null) {
      this.getNewPrice()
    } else {
      this.propsOrder()
    }
  }

  showInput = () => {
    this.setState({
      showIndex: 1
    })
  }

  changeServicePrice = (v, i, e) => {
    this.setState({
      servicePrice: e
    })
  }

  cashierRemarkChange = (e) => {
    this.setState({
      cashierRemark: e.target.value
    })
  }

  discountDialogSave = (v,i) => {
    let {servicePrice} = this.state 
    let e = servicePrice
    let price = this.discountPriceRef.input.value
    let cashierRemark = this.discountReasonRef.input.value
    if(servicePrice === undefined) {
      e = {target:{ value: price }}
    }
    if(!price || !cashierRemark) {
      React.$message({
        type: 'warning',
        content: '请输入金额和原因'
      })
      return
    }else {
      v.cashierRemark = cashierRemark
      this.props.changeServicePrice(v, i, e)
      this.setState({
        showIndex: 0
      })
    }
  }
  render() {
    const { info } = this.props
    const { discountPrice, bgColor, initialValues, petOption, visible, days, roomName, showIndex, cashierRemark } = this.state
    return (
      <div className='tab-item service' style={{ marginBottom: 20, backgroundColor: bgColor, border: 'none' }}>
        <div className='tab-item-name'>
          {roomName}
          {[1, 3].includes(info.roomStatus) && <Tooltip placement="bottomLeft" title={[
            <h3 style={{ color: '#FFF' }}>该房间{info.roomStatus === 1 ? "已被预留" : "正在维修中"}</h3>,
          ]}>
            <span className="tips" style={{
              display: 'inline-block',
              width: '20px',
              height: ' 20px',
              fontSize: '12px',
              lineHeight: '20px',
              textAlign: 'center',
              borderRadius: '50%',
              backgroundColor: '#000',
              color: '#fff',
              cursor: ' pointer',
              marginLeft: '10px'
            }}>!</span>
          </Tooltip> || info.roomStatusDateVoList.length > 0 && <Tooltip placement="bottomLeft" title={[
            <h3 style={{ color: '#FFF' }}>已{info.hotelHomeStatus === 4 ? "被预定" : "入住"}时间：</h3>,
            info.roomStatusDateVoList.map(v => {
              return <>
                <p>{v.beginTime + '~' + v.endTime}</p>
              </>
            })

          ]}>
            <span className="tips" style={{
              display: 'inline-block',
              width: '20px',
              height: ' 20px',
              fontSize: '12px',
              lineHeight: '20px',
              textAlign: 'center',
              borderRadius: '50%',
              backgroundColor: '#000',
              color: '#fff',
              cursor: ' pointer',
              marginLeft: '10px'
            }}>!</span>
          </Tooltip>
          }
        </div>
        <CloseOutlined onClick={() => this.outCar(info, 'service')} style={{ position: 'absolute', top: 5, right: 5, cursor: 'pointer' }} />
        <Form
          labelCol={{
            span: 6,
          }}
          wrapperCol={{
            span: 14,
          }}
          validateTrigger="onChange"
          layout="horizontal"
          ref={ref => this.formRef = ref}
          onValuesChange={(v) => this.onValuesChange(v)}
          initialValues={initialValues}
        >
          <Form.Item label="入住时间" name="beginTime" rules={[{ required: true }]} >
            <DatePicker disabledDate={this.disabledDate} />
          </Form.Item>
          <Form.Item label="离店时间" name="endTime" rules={[{ required: true }]} >
            <DatePicker disabledDate={this.disabledDateEnd} />
          </Form.Item>
          <div style={{ color: '#D9001B', marginLeft: '30%', marginTop: '-9%' }}>共计入住：{days + 1 + '天' + days + '晚'} </div>
          <Form.Item label="宠物信息" name="petName" rules={[{ required: true }]}>
            <Select >
              {petOption.map((v, index) => {
                return <Option key={index} value={v.petArchivesId} >{v.petName}</Option>
              })}
            </Select>
          </Form.Item>
          <div style={{ marginLeft: '30%', marginTop: '-9%' }}><Button type='link' onClick={() => this.createPet()} >新建并绑定宠物</Button></div>
          <Form.Item label="宠主昵称" name="memberName" rules={[{ required: true }]} >
            <Input maxLength={10} />
          </Form.Item>
          <Form.Item label="手机号码" name="memberMobile" rules={[{ required: true }, { pattern: phoneReg, message: '请输入正确的手机号!' }]} >
            <InputNumber />
          </Form.Item>
          {/* <Form.Item label="价格" hidden name="price">
                        <Input />
                    </Form.Item> */}

        </Form>
        <div className='tab-item-bottom'>
          <div>
            {/* {
              showIndex !== 1 && <> */}
            <div className='symbol'>￥</div>
            <div className="price">
              <React.$Price color="#ef3800" price={info.serviceRealPrice} symbol={''} />
              <FormOutlined onClick={() => this.showInput()} style={{ fontSize: 16, marginLeft: 10, cursor: 'pointer', color: '#000' }} />
            </div>
            {/* </>
            } */}
            {/* {
              showIndex === 1 && <Input
                autoFocus
                precision={2}
                min={0}
                defaultValue={React.$transNum(info.serviceRealPrice, 2, -2)}
                onPressEnter={(e) => this.changeServicePrice(info, null, e)}
              />
            } */}
          </div>
        </div>
        <Modal visible={visible}
          title="新建并绑定宠物"
          labelCol={{
            span: 6,
          }}
          wrapperCol={{
            span: 14,
          }}
          onCancel={this.onCancel}
          footer={null}
          width={'50%'}
          // forceRender
          destroyOnClose={true}
        >
          <PetInfoAdd ref={this.PetInfoAdd} cancel={this.onCancel} bindPet={(value) => this.createBindPet(value)} />
        </Modal>
        <CashierModal
          title={'其他服务'}
          visible={showIndex}
          onCancel={() => { this.setState({ showIndex: 0 }) }}
          onOk={()=>this.discountDialogSave(info, null)}
          width={400}
        >
          <div className='discount cashier-modal-input-box'>
              <span>金额</span>
              <Input
                allowClear
                style={{ width: 300 }}
                placeholder='请输入金额'
                defaultValue={React.$transNum(info.serviceRealPrice, 2, -2)}
                ref={ref => this.discountPriceRef = ref}
                min={0}
                precision={2}
                onChange={e=>{this.changeServicePrice(info, null, e)}} />
            </div>
            <div className='discount cashier-modal-input-box'>
              <span>原因</span>
              <Input
                allowClear
                maxLength={30}
                style={{ width: 300 }}
                placeholder='请输入原因'
                value={cashierRemark}
                ref={ref => this.discountReasonRef = ref}
                onChange={(e)=>this.cashierRemarkChange(e)} />
            </div>
        </CashierModal>
      </div>
    );
  }
}
